import { Injectable } from '@angular/core';
import { HttpProvider } from '../http/http';
/*
  Generated class for the AmapProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
declare var AMap;
@Injectable()
export class AmapProvider {

	constructor(public http: HttpProvider) {
		console.log('Hello AmapProvider Provider');
	}

	/**
	 * 初始化地图
	 * @param id 
	 */
	public initMap(id: any) {
		return new AMap.Map(id, {
			resizeEnable: true,
			zoom: 8,
			center: [116.39, 39.9]
		});
	}

	/**
	 * 地图插件
	 */
	public initMapPlugins(map: any) {
		let promise = new Promise((success, fail) => {
			AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.Geolocation'], function() {
				map.addControl(new AMap.ToolBar());
				map.addControl(new AMap.Scale());
				if(success)
					success();
			});
		});
		//异步回调
		return promise;
	}

	/**
	 * 定位操作
	 */
	public initGeolocation(map: any) {
		let promise = new Promise((success, fail) => {
			AMap.plugin(['AMap.Geolocation'], function() {
				let geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 10000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				});
				map.addControl(geolocation);
				geolocation.getCurrentPosition();
				AMap.event.addListener(geolocation, 'complete', function(result) {
					//设置当前定位坐标
					if(success)
						success(result);
				}); //返回定位信息
				AMap.event.addListener(geolocation, 'error', function(error) {
					if(fail)
						fail(error);
				});
			});
		});
		//异步回调
		return promise;
	}

	/** 
	 * 标注
	 */
	public initMarker(lng: any, lat: any) {
		let marker = new AMap.Marker({
			icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
			position: [lng, lat],
			clickable: true
		});
		return marker;
	}

	/**
	 * 延迟执行器
	 */
	public initTimer(map: any, seccess: any) {
		let that = this;
		that.initGeolocation(map).then(result => {
			this.httpPost(result['position']);
			this.sendObserver(seccess, 1);
		}, error => {
			this.sendObserver(seccess, 0);
		});
		setTimeout(() => {
			that.initTimer(map,seccess);
		},5000);
	}

	/**
	 * @param Observer 订阅消息
	 */
	public sendObserver(Observer: any, val: any) {
		Observer.next(val);
	}

	/**
	 * 定位上传
	 */
	public httpPost(position: any) {
		this.http.postJson('positionpost', 'codeauth', {
			'lat': position.lat,
			'lng': position.lng
		}, false).then(res => {
			//提交成功
		}, fail => {
			//提交失败
		});
	}
}